package at.fhooe.obd.tasks;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.inputmethodservice.Keyboard.Key;
import android.os.AsyncTask;
import at.fhooe.obd.gui.DisplayTrackActivity;
import at.fhooe.obd.gui.Keys;

public class GetTrackByIdTask extends AsyncTask<String, Integer, JSONObject> {

	private static final String URL = "http://obdproject.hostoi.com/requestTrack.php?trackID=";
	private boolean testMode = false;
	private DisplayTrackActivity activity = null;

	List<String> labelIgnoreList = Arrays.asList(new String[] { 
			Keys.JSON_LATITUDE, 
			Keys.JSON_LONGITUDE, 
			Keys.JSON_ALTITUDE, 
			Keys.JSON_TRACK_ID, 
			Keys.JSON_TIME});

	public GetTrackByIdTask(DisplayTrackActivity activity) {
		this.activity = activity;
	}

	@Override
	protected JSONObject doInBackground(String... params) {
		String trackId = params[0];

		if (testMode) {
			String bla = "{\n"
					+ "	\"track\" : {\n"
					+ "		\"id\" : 1,\n"
					+ "		\"date\" : \"2012-26-11\",\n"
					+ "		\"user\" : {\n"
					+ "			\"userID\" : 1337,\n"
					+ "			\"userName\" : \"Test-User\"\n"
					+ "		},\n"
					+ "		\"car\" : {\n"
					+ "			\"carID\" : 123,\n"
					+ "			\"carName\" : \"BMW 3\",\n"
					+ "			\"carHorsePower\" : 120\n"
					+ "		},\n"
					+ "		\"trackData\" : [\n"
					+ "			{ \"trackDataID\" : 1, \"lat\" : \"5365456.55\", \"long\" : \"5456546.656\", \"alt\" : \"100.0\", \"consumption\" : 5.0, \"speed\" : 53.0 },\n"
					+ "			{ \"trackDataID\" : 2, \"lat\" : \"5365456.55\", \"long\" : \"5456546.656\", \"alt\" : \"100.0\", \"consumption\" : 5.0, \"speed\" : 57.0 }\n"
					+ "		]\n" + "	}\n" + "}";

			JSONObject object = null;
			try {
				object = new JSONObject(bla);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return object;
		} else {
			String json = JsonDownloadHelper.downloadJson(URL, trackId);
			JSONObject obj = null;

			try {
				obj = new JSONObject(json);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return obj;
		}

	}

	@Override
	protected void onPostExecute(JSONObject result) {
		try {
			
			JSONObject user = result.getJSONObject(Keys.JSON_USER);
			String userName = user.getString(Keys.JSON_USER_NAME);
			
			JSONObject car = result.getJSONObject(Keys.JSON_CAR);
			String carName = car.getString(Keys.JSON_CAR_NAME);
			String horses = String.valueOf(car.getInt(Keys.JSON_CAR_HORSES));
			
			String date = result.getString(Keys.JSON_DATE);
			
			this.activity.setTrackInfo(userName, carName, horses, date);
			
//			JSONArray trackArray = result.getJSONObject("track").getJSONArray("trackData");
			JSONArray trackArray = result.getJSONArray(Keys.JSON_TRACKS);
			Map<String, List<Double>> doubleValueMap = new HashMap<String, List<Double>>();
			Map<String, List<String>> stringValueMap = new HashMap<String, List<String>>();
			List<String> allLabels = new ArrayList<String>();

			String s = "";
			for (int i = 0; i < trackArray.length(); i++) {
				JSONObject jsonObject = trackArray.getJSONObject(i);

				Iterator<String> it = jsonObject.keys();

				// loop over the value set of the given track data
				// in case values are not set or they don't have the
				// right type they are filtered out
				while (it.hasNext()) {
					String trackValue = it.next();

					Object o = jsonObject.get(trackValue);

					// fill string data in a string map
					if (o instanceof String) {
						if (!allLabels.contains(trackValue) && !labelIgnoreList.contains(trackValue))
							allLabels.add(trackValue);

						if (!stringValueMap.containsKey(trackValue))
							stringValueMap.put(trackValue, new ArrayList<String>());

						stringValueMap.get(trackValue).add(o.toString());
						// Log.i("", trackValue + " is String");
					}
					// fill double (and integer) data in a double map
					else if (o instanceof Double || o instanceof Integer) {
						if (!allLabels.contains(trackValue) && !labelIgnoreList.contains(trackValue))
							allLabels.add(trackValue);
						
						if (!doubleValueMap.containsKey(trackValue))
							doubleValueMap.put(trackValue, new ArrayList<Double>());

						if (o instanceof Integer)
						{
							doubleValueMap.get(trackValue).add(Double.parseDouble(o.toString()));
						}
						else
							doubleValueMap.get(trackValue).add((Double) o);
						// Log.i("", trackValue + " is double value");
					}
					// else if (o instanceof Integer)
					// {
					//
					// }
					// Log.i("", trackValue);
				}
				s = jsonObject.getString("speed");
				// Log.i("", "Object from array, pos " + i + ": " +
				// jsonObject.toString());
			}

			activity.setDoubleMap(doubleValueMap);
			activity.setStringMap(stringValueMap);
			activity.setAllLabels(allLabels);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
